import React, { useMemo, useState, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import '@/app/component/form.css';
import classNames from 'classnames';
import { X } from 'lucide-react';

/** 辅助类型：根据多选状态推导值类型 */
type InputValue<T, IsNumber> = IsNumber extends true ? number | undefined : string | undefined;
interface MyInputProps<T, IsNumber extends boolean = false> {
  value?: InputValue<T, IsNumber>;
  onChange?: (value: InputValue<T, IsNumber>) => void;
  onBlur?: () => void;
  onClear?: () => void; // 新增清空回调
  placeholder?: string;
  disabled?: boolean;
  prefix?: React.ReactNode;
  suffix?: React.ReactNode;
  number?: IsNumber; // 绑定是否是数字输入
  max?: number;
  min?: number;
  precision?: number;
  className?: string; // 自定义类名
}

const MyInput = <T, IsNumber extends boolean = false>({
  value: propsValue, // 外部传入的原始值
  onChange,
  onBlur,
  onClear,
  placeholder,
  disabled,
  suffix,
  prefix,
  number,
  max,
  min,
  precision,
  className,
}: MyInputProps<T, IsNumber>) => {
  // 核心修改：用对象包装值，确保引用变化触发更新
  const [innerValue, setInnerValue] = useState<{ value: InputValue<T, IsNumber> }>({
    value: propsValue,
  });

  // 同步外部 props.value 到内部对象状态（外部更新时同步）
  useEffect(() => {
    setInnerValue({ value: propsValue });
  }, [propsValue]);

  const [isFocus, setIsFocus] = useState(false);

  // 判断是否是有效value值（基于内部对象的value）
  const isStringValid = useMemo(() => {
    return innerValue.value !== undefined && innerValue.value !== '';
  }, [innerValue.value]);

  const isNumberValid = useMemo(() => {
    return innerValue.value !== undefined && !isNaN(Number(innerValue.value));
  }, [innerValue.value]);

  // 输入处理：字符串
  const handleStringChange = (value: string | undefined) => {
    let processedValue: string | undefined = value;
    if (value === undefined) {
      processedValue = undefined;
    } else if (max !== undefined && value.length > max) {
      processedValue = value.slice(0, max) as string;
    }

    // 更新内部对象状态（引用变化触发更新）
    setInnerValue({ value: processedValue as InputValue<T, IsNumber> });
    // 对外传递原始值类型
    onChange?.(processedValue as InputValue<T, IsNumber>);
  };

  // 输入处理：数字
  const handleNumberChange = (value: string | undefined) => {
    let processedValue: number | undefined = undefined;

    if (value !== undefined && value !== '' && !isNaN(Number(value))) {
      let num = Number(value);
      // 处理精度
      if (precision !== undefined && precision >= 0) {
        num = Number(num.toFixed(precision));
      }
      processedValue = num;
    }

    // 更新内部对象状态（引用变化触发更新）
    setInnerValue({ value: processedValue as InputValue<T, IsNumber> });
    // 对外传递原始值类型
    onChange?.(processedValue as InputValue<T, IsNumber>);
  };

  // 处理失去焦点时的min/max限制
  const handleBlur = () => {
    setIsFocus(false);
    
    // 仅在数字模式且值有效时处理
    if (number && isNumberValid) {
      const currentValue = Number(innerValue.value);
      let adjustedValue: number | undefined = currentValue;
      
      // 处理最小值限制
      if (min !== undefined && !isNaN(min) && currentValue < min) {
        adjustedValue = min;
      }
      
      // 处理最大值限制
      if (max !== undefined && !isNaN(max) && currentValue > max) {
        adjustedValue = max;
      }
      
      // 处理精度（确保调整后的值仍符合精度要求）
      if (precision !== undefined && precision >= 0 && adjustedValue !== undefined) {
        adjustedValue = Number(adjustedValue.toFixed(precision));
      }
      
      // 如果值有调整，更新状态并触发回调
      if (adjustedValue !== currentValue) {
        setInnerValue({ value: adjustedValue as InputValue<T, IsNumber> });
        onChange?.(adjustedValue as InputValue<T, IsNumber>);
      }
    }
    
    // 触发外部onBlur回调
    onBlur?.();
  };

  return (
    <div
      className={classNames('input-layout', {
        'input-layout--focus': isFocus,
        'input-layout--disabled': disabled,
        'input-layout--placeholder': number ? !isNumberValid : !isStringValid,
      }, className)}
    >
      {prefix}
      <Input
        min={min}
        max={max}
        type={number ? 'number' : 'text'}
        className='input-text'
        placeholder={placeholder}
        // 使用内部对象的value
        value={innerValue.value ?? ''}
        onChange={(e) =>
          number ? handleNumberChange(e.target.value) : handleStringChange(e.target.value)
        }
        onFocus={() => setIsFocus(true)}
        onBlur={handleBlur} // 使用新的处理函数
        disabled={disabled}
      />
      {/* 字符串最大值指示器 */}
      {!number && max !== undefined && (
        <div className='input-text-max'>
          {typeof innerValue.value === 'string' ? innerValue.value.length : 0} / {max}
        </div>
      )}
      {/* 清空按钮 */}
      <div className='input-indicator'>
        <div className='input-indicator-container'>
          <X
            className={classNames('input-indicator-close transition-all duration-100', {
              'hidden': number ? !isNumberValid : !isStringValid || disabled,
            })}
            onClick={(e) => {
              e?.stopPropagation();
              number ? handleNumberChange('') : handleStringChange('');
              // 调用清空回调
              onClear?.();
            }}
          />
        </div>
      </div>
      {suffix}
    </div>
  );
};

export default MyInput;
    